package service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import common.impl.exception.ServiceException;


import model.MAuthority;
import model.MGroup;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.interf.IAuthority;
import dao.interf.IAuthorityDAO;
import dao.interf.IGroupAuthorityDAO;
import dao.interf.IGroupDAO;
import dao.interf.IGroupUserDAO;
import dao.interf.IUserDAO;
import dao.pojo.Authority;
import dao.pojo.Group;
import dao.pojo.GroupAuthority;
import dao.pojo.GroupUser;
import dao.pojo.User;

public class AuthorityImpl implements IAuthority{
	
	private IGroupDAO groupDao;
	private IAuthorityDAO authDao;
	private IGroupAuthorityDAO gauthDao;
	private IGroupUserDAO guserDao;
	private IUserDAO userDao;

	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}

	public void setGroupDao(IGroupDAO groupDao) {
		this.groupDao = groupDao;
	}
	
	public void setAuthDao(IAuthorityDAO authDao) {
		this.authDao = authDao;
	}

	public void setGauthDao(IGroupAuthorityDAO gauthDao) {
		this.gauthDao = gauthDao;
	}

	public void setGuserDao(IGroupUserDAO guserDao) {
		this.guserDao = guserDao;
	}

	/************ GROUP *********/
	/**
	 * 添加组
	 * @param model
	 * 		组
	 * @return "1"
	 */
	public String addGroup(MGroup model) throws Exception {
		Group group = new Group();
		group.setGroupName(model.getGroupName());
		groupDao.save(group);
		return "1";
	}
	
	/**
	 * 删除组通过id
	 * @param groupId
	 * 		组id
	 * @return 1
	 */
	public String delGroup(Integer groupId) throws Exception {
		groupDao.delById(groupId);
		return "1";
	}
	
	/**
	 * 批量更新组
	 * @param datas
	 *        数据集
	 * @return "1"
	 *        更新成功
	 */
	public String batchUpdateGroup(String datas) throws Exception {
		JSONArray jarr = JSONArray.fromObject(datas);
		for(int i=0,len=jarr.size(); i < len; i++) {
			JSONObject jobj = jarr.getJSONObject(i);
			Group group = new Group();
			int flag = jobj.getInt("flag");			
			switch(flag){
			case 1: //添加
				group.setGroupName(jobj.getString("groupName"));
				groupDao.save(group);
				break;
			case 2:  //编辑
				group = (Group)groupDao.findById((Integer)jobj.getInt("groupId"));
				if(jobj.containsKey("groupName") && !"".equals(jobj.getString("groupName")))
					group.setGroupName(jobj.getString("groupName"));
				groupDao.update(group);
				break;
			case 3:  //删除
				groupDao.delById((Integer)jobj.getInt("groupId"));
				break;
			}
		}
		return "1";
	}
	

	/********* AUTHORITY *******************/
	/**
	 * 添加权限
	 * @param model
	 *        权限model
	 * @return "1"
	 *        添加成功
	 * @throws Exception
	 */
	public String addAuthority(MAuthority model) throws Exception {
	    Authority authority = new Authority();
	    authority.setAuthorityName(model.getAuthorityName());
		authDao.save(authority)	;    
	    return "1";
	}
	
	/**
	 * 删除权限，通过权限名
	 * @param aname
	 *        权限名
	 * @return "1"
	 *        删除成功
	 * @throws Exception
	 */
	public String delAuthority(String aname) throws Exception {
		Authority auth = authDao.findByProperties(new String[]{"authorityName"}, 
				new Object[]{aname}).get(0);
	    authDao.del(auth);
		return "1";
	}
	
	////////测试！！
	/**
	 * 批量更新权限
	 * @param datas
	 *        数据集
	 * @return "1"
	 *        更新成功
	 * @throws Exception
	 */
	public String batchUpdateAuthority(String datas) throws Exception {
		JSONArray jarr = JSONArray.fromObject(datas);
		for(int i=0,len=jarr.size();i<len;i++){
			JSONObject jobj = jarr.getJSONObject(i);
			int flag = jobj.getInt("flag");
			switch(flag){
			case 1: //添加
				String authname = jobj.getString("authorityName");
				Authority authority = new Authority();
				authority.setAuthorityName(authname);
				authDao.save(authority);
				break;
			case 2:  //编辑
				
				break;
			case 3:  //删除
			    Authority auth = (Authority) authDao.findByProperties(new String[]{"authorityName"}, 
			    		new Object[]{ jobj.getString("authorityName") });
			    authDao.del(auth);
				break;
			}
		}
		return "1";
	}
	
	/********** GROUP_AUTHORITY ************/
	
	public String addGroupAuthorities(Integer groupId, String authorities)
			throws Exception {
		if(null == groupId || null == authorities) {
			throw new ServiceException("ERR-");
		}
		Group g = groupDao.findById(groupId);
		String[] auths = authorities.split(",");
		int len = auths.length;
		for(int i = 0; i < len; i++) {
			Authority a = null;
			a = (Authority) authDao.findById(auths[i]);
			GroupAuthority ga = new GroupAuthority();
			ga.setGroup(g);
			ga.setAuthority(a);
			gauthDao.save(ga);
		}
		return "1";
	}
	

	/**
	 * 删除组权限
	 * @param groupId
	 * @param authorities
	 * @return "1"
	 *         成功
	 * @throws Exception
	 */
	public String delGroupAuthority(Integer groupId, String authorities)
			throws Exception {
		if(null == groupId || null == authorities) {
			throw new ServiceException("ERR-");
		}
		
		String[] auths = authorities.split(",");
		int len = auths.length;
        for(int i = 0; i < len; i++) {		
        	GroupAuthority ga = gauthDao.findByProperties(new String[] {"groupId", "authorityId"}, 
        			new Object[]{groupId, auths[i]}).get(0);
        	//组权限不为空，则可以删除。
        	if(null != ga) {
        		gauthDao.del(ga);
        	}
        }
		return "1";
	}

	/**
	 * 删除组所有的权限
	 * @param groupId
	 * @return "1"
	 * @throws Exception
	 */
	public String delGroupAllAuthority(Integer groupId) throws Exception {
		List<GroupAuthority> gas = gauthDao.findByProperties(new String[]{"groupId"},
				new Object[]{groupId});
		gauthDao.batchDel(gas);
		return "1";
	}

	//更新组权限，待测试！！
	public String updateGroupAuthority(Integer groupId, String authorities)
			throws Exception {
		String result = delGroupAllAuthority(groupId);
		if(!result.equals("1")) return result;

		return addGroupAuthorities(groupId, authorities);
	}
	
	/************* GROUP_MEMBER *********************/

	/**
	 * 添加用户到多个组
	 * @param userId
	 * @param groups
	 * @return "1"
	 *       添加成功
	 * @throws Exception
	 */
	public String addUserToGroups(Integer userId, String groups) throws Exception {
		
		if(null == userId || null == groups) {
			throw new ServiceException("ERR-");
		}
		String[] gs = groups.split(",");
		User user = userDao.findById(userId);
		int len = gs.length;
		for(int i = 0; i < len; i++) {
			GroupUser gu = new GroupUser();
			gu.setUser(user);
			Group group = groupDao.findById(gs[i]);
			gu.setGroup(group);
			guserDao.save(gu);
		}
		return "1";
	}
	/**
	 * 添加用户到组, 通过组名
	 * @param userId
	 * @param groupName
	 * @return "1"
	 *         添加成功
	 * @throws Exception
	 */
	public String addUserToGroup(Integer userId, String groupName)
			throws Exception {
		if(null == userId || null == groupName) {
			throw new ServiceException("ERR-");
		}
		
		Group group = groupDao.findByProperties(new String[]{"groupName"}, 
				new Object[]{groupName}).get(0);
		User user = userDao.findById(userId);
		
		if(null== group || null == user) {
			throw new ServiceException("ERR-");
		}
		
		GroupUser gu = new GroupUser();
		gu.setUser(user);
		gu.setGroup(group);
		guserDao.save(gu);
		return "1";
	}

	/**
	 * 添加多个用户到组
	 * @param users
	 *        userid组成的字符串
	 * @param groupId
	 *        组id
	 * @return "1"
	 *  	    添加成功
	 * @throws Exception
	 */
	public String addUsersToGroup(String users, Integer groupId)
			throws Exception {
	  	if(null == users || null == groupId) {
			throw new ServiceException("ERR-");
		}
	  	
	  	Group group = groupDao.findById(groupId);
	  	if(null == group) {
	  		throw new ServiceException("ERR-");
	  	}
	  	
	  	String[] us = users.split(",");
	  	int len = us.length;
	  	for(int i = 0; i < len; i++) {
	  		GroupUser gu = new GroupUser();
	  		gu.setGroup(group);
	  		User u = userDao.findById(us[i]);
	  		if(null == u) {
	  			continue;
	  		}
	  		gu.setUser(u);
	  		guserDao.save(gu);
	  	}
		return "1";
	}

	/**
	 * 从多个组中删除某一用户
	 * @param userId
	 * @param groups
	 * @return "1"
	 *  	成功
	 * @throws Exception
	 * 
	 */
	public String removeUserFromGroups(Integer userId, String groups)
			throws Exception {
		if(null == userId || null == groups) {
			throw new ServiceException("ERR-");
		}
		
		String[] gs = groups.split(",");
		int len = gs.length;
        for(int i = 0; i < len; i++) {		
        	GroupUser gu = guserDao.findByProperties(new String[] {"userId", "groupId"},
        			new Object[]{userId, gs[i]}).get(0);
        	guserDao.del(gu);
        }
		return "1";
		
	}
	
	/**
	 * 从一个组中删除多个用户
	 * @param users
	 *        userid组成的字串
	 * @param groupId
	 *        组id
	 * @return "1"
	 *        成功
	 * @throws Exception
	 */
	public String removeUsersFromGroup(String users, Integer groupId)
	throws Exception {
		if(null == groupId || null == users) {
			throw new ServiceException("ERR-");
		}
		
		String[] us = users.split(",");
		int len = us.length;
        for(int i = 0; i < len; i++) {		
        	GroupUser gu = guserDao.findByProperties(new String[] {"groupId", "userId"},
        			new Object[]{groupId, us[i]}).get(0);
        	guserDao.del(gu);
        }
		return "1";
	}
	
	/**
	 * 从单个组中删除单个用户
	 */
	public String removeUserFromGroup(Integer userId, Integer groupId)
	throws Exception {
		if(null == userId || null == groupId) {
			throw new ServiceException("ERR-");
		}
		
		GroupUser gu = guserDao.findByProperties(new String[]{"userId", "groupId"},
				new Object[]{userId, groupId}).get(0);
		guserDao.del(gu);
		return "1";
	}
	
	/**
	 * 从用户所在组
	 */
	public String removeUserGroups(Integer userId) throws Exception {
		List<GroupUser> gus = guserDao.findByProperties(new String[] {"userId"},
				new Object[]{userId});
		guserDao.batchAdd(gus);
		return "1";
	}
	
	
	/********************* 获取 *************************/
	/**
	 * 获取用户所有组
	 * @param userId
	 *        用户id
	 * @return JSONArray
	 * @throws Exception
	 */
	public String getUserGroups(Integer userId) throws Exception {
		List<GroupUser> gus = guserDao.findByProperties(new String[] {"userId"},
				new Object[]{userId});
		JSONArray jarr = new JSONArray();
		if(!gus.isEmpty()) {
			for(GroupUser gu : gus) {
				JSONObject jobj = new JSONObject();
				Group g = gu.getGroup();
				jobj.put("groupId", g.getGroupId());
				jobj.put("groupName", g.getGroupName());
				jarr.add(jobj);				
			}
		}
		return jarr.toString();
	}

	public String getUserGroups(String userName) throws Exception {
		if(null == userName || userName.isEmpty()) {
			throw new ServiceException("ERR-");
		}
		Integer userId = userDao.findByProperties(new String[]{"userName"}, 
				new Object[]{userName}).get(0).getUserId();
		
		return getUserGroups(userId);
	}
	
	public String updateUserGroups(String userName, String groups)
				throws Exception {
		User u = null;
		List<User> uLst = userDao.findByProperties(new String[]{"userName"},new Object[]{userName});
		if(null != uLst && !uLst.isEmpty())
			u = uLst.get(0);
		if(null == u)
			throw new ServiceException("ERR-");
		
		return addUserToGroups(u.getUserId(), groups);
	}
	
	//测试！
	public String updateGroupUsers(String users, Integer groupId)
			throws Exception {
		Group g = (Group)groupDao.findById(groupId);
		if(null == g)
			throw new ServiceException("ERR-0017");
		if(null != users)
			return addUsersToGroup(users, groupId);
		return "1";
	}
	
	public String getGroupUsers(Integer groupId) throws Exception {
	    if(null == groupId) {
	    	throw new ServiceException("ERR-");
	    }
	    List<GroupUser> guLst = guserDao.findByProperties(new String[]{"groupId"},
	    		new Object[]{groupId});
	    JSONArray jarr = new JSONArray();
	    if(!guLst.isEmpty()){
	    	for(GroupUser gu : guLst) {
	    		JSONObject jobj = new JSONObject();
	    		User user = null;
	    	    user = gu.getUser();
	    	    if(null != user) {
	    	    	jobj.put("userId", user.getUserId());
	    	    	jobj.put("userName", user.getUserName());
	    	    	jarr.add(jobj);
	    	    }
	    	}
	    }
		return jarr.toString();
	}
	
	/**
	 * 获取所有权限，暂时不进行分页
	 */
	public String getAllAuthorities(int page, int rows) throws Exception {
		
		JSONArray jarr = new JSONArray();
		List<Authority> authLst = authDao.findAll();
		if(!authLst.isEmpty()) {
			for(Authority auth : authLst) {
				JSONObject jobj = new JSONObject();
				jobj.put("authorityId", auth.getAuthorityId());
				jobj.put("authority", auth.getAuthorityName());
				jarr.add(jobj);
			}
		}
		
		return jarr.toString();
	}

	/**
	 * 获取所有组，暂时不进行分页
	 * @param page
	 * @param rows
	 * @return JSONArray
	 * @throws Exception
	 */
	public String getAllGroups(int page, int rows) throws Exception {
		JSONArray jarr = new JSONArray();
		List<Group> groups = groupDao.findAll();
		JSONObject jret = new JSONObject();
		if(!groups.isEmpty()) {
			for(Group g : groups) {
				JSONObject jobj = new JSONObject();
				jobj.put("groupId",   g.getGroupId());
				jobj.put("groupName", g.getGroupName());
				jarr.add(jobj);
			}
		}
		jret.put("rows", jarr);
		return jret.toString();
	}

	/**
	 * 获取所有组并带权限
	 * @return 权限json串 [{groupName:[auth1,auth2,...]},......]
	 */
	public String getAllGroupsWithAuthority() throws Exception {
		List<Group> lst = null;
		lst = groupDao.findAll();
		JSONObject jobj = new JSONObject();
		
		if (null != lst) {
			for (Iterator<Group> l = lst.iterator(); l.hasNext();) {
				Group group = l.next();
				List<GroupAuthority> lst1 = gauthDao.findByProperties(new String[]{"groupId"},
						new Object[]{group.getGroupId()});
				
				ArrayList<String> arrAuth = new ArrayList<String>();
				//处理组权限
				if (null != lst1){
					for (Iterator<GroupAuthority> it = (Iterator<GroupAuthority>) lst1
							.iterator(); it.hasNext();) {
						GroupAuthority ga = it.next();
						if (null != ga) {
							Authority auth = ga.getAuthority();
							if (null != auth) {
								arrAuth.add("'" + auth.getAuthorityName() + "'");
							}
						}
					}
				}
				jobj.put(group.getGroupName(), arrAuth.toString());
			}
		}
		//debug pass
		return jobj.toString();
	}

	/**
	 * 获取某一权限的所有用户
	 * @return JSONArray
	 */
	public String getUsersByAuthority(Integer authId) throws Exception {
		Authority authority = authDao.findById(authId);
		if(null == authority) {
			throw new ServiceException("ERR-");
		}
		List<User> userLst = userDao.findUserByAuthority(authority);
		JSONArray jarr = new JSONArray();
		if(!userLst.isEmpty()) {
			for(User u : userLst) {
				JSONObject jobj = new JSONObject();
				jobj.put("userId", u.getUserId());
				jobj.put("userName", u.getUserName());
				jobj.put("loginTime", u.getLoginTime());
			    jarr.add(jobj);
			}
		}
		return jarr.toString();
	}

	/**
	 * 获取组权限
	 */
	public String getAuthsByGroup(Integer groupId) throws Exception {
		if(null == groupId) {
			throw new ServiceException("ERR-");
		}
		List<GroupAuthority> gauths = gauthDao.findByProperties(new String[]{"groupId"},
				new Object[]{groupId});
		JSONArray jarr = new JSONArray();
		if(!gauths.isEmpty()) {
			for(GroupAuthority ga : gauths) {
				JSONObject jobj = new JSONObject();
				Authority auth = ga.getAuthority();
				jobj.put("authorityId", auth.getAuthorityId());
				jobj.put("authority", auth.getAuthorityName());
                jarr.add(jobj);				
			}
		}
		return jarr.toString();
	}
	/**
	 * 获取用户所有权限
	 */
	public String getAuthoritiesByUser(Integer userId) throws Exception {
		User user = userDao.findById(userId);
		if(null == user) {
			throw new ServiceException("ERR-");
		}
		List<Authority> authLst = authDao.findAuthorityByUser(user);
		JSONArray jarr = new JSONArray();
		if(!authLst.isEmpty()) {
			for(Authority auth : authLst) {
				JSONObject jobj = new JSONObject();
				jobj.put("authorityId", auth.getAuthorityId());
				jobj.put("authority", auth.getAuthorityName());
				jarr.add(jobj);
			}
			
		}
		return jarr.toString();
	}

	/**
	 * 检查用户是否有权限
	 */
	public boolean isUserHasAuthority(Integer userId, String auth)
			throws Exception {
		User user = userDao.findById(userId);
		if(null == user) {
			throw new ServiceException("ERR-");
		}
		List<Authority> arr = authDao.findAuthorityByUser(user);
		if(null != arr){
			int len = arr.size();
			for(int i=0; i<len; i++){
				if(arr.get(i).getAuthorityName().equals(auth))
					return true;
			}
		}
		return false;
	}


	public String getGroupUsersDetail(Integer groupId, int pageno, int pagesize)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	

}
